

const { ccclass, property } = cc._decorator;

@ccclass
export default class Util extends cc.Component {

    static mInstance = null;
    public mNodePool: Map<string, cc.NodePool> = new Map();
    public static instance(): Util {
        if (this.mInstance == null) {
            this.mInstance = new Util();
        }
        return this.mInstance;
    }
    //对象池创建
    CreatePool(item: cc.Prefab) {
        let pool = new cc.NodePool;
        for (var index = 0; index < 5; index++) {
            let itemPrefab = cc.instantiate(item);
            pool.put(itemPrefab);
        }
        this.mNodePool.set(item.name, pool);
    }

    /**
     * 从对象池取出       
     * 参数1: item-预制
     */
    pool(item: cc.Prefab): cc.Node {
        if (this.mNodePool.has(item.name)) {
            if (this.mNodePool.get(item.name).size() > 0) {
                return this.mNodePool.get(item.name).get();
            } else {
                let itemPrefab = cc.instantiate(item);
                this.mNodePool.get(item.name).put(itemPrefab);
                return this.mNodePool.get(item.name).get();
            }
        } else {
            this.CreatePool(item);
            return this.mNodePool.get(item.name).get();
        }
    }

    /**
     * 回收       
     * 参数1: item-节点
     */
    put(item: cc.Node) {
        if (this.mNodePool.has(item.name)) {
            this.mNodePool.get(item.name).put(item);
        }
    }
}
